package com.zr.controller;

import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import net.sf.json.JSONObject;

import com.zr.model.Customer;
import com.zr.model.Dish_spd;
import com.zr.service.DishServiceImpl_spd;
import com.zr.service.DishService_spd;

public class DishController_spd extends HttpServlet{
	DishService_spd ds = new DishServiceImpl_spd();
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		doPost(req, resp);
	}
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		resp.setCharacterEncoding("utf-8");
		HttpSession session = req.getSession();
		PrintWriter pw = resp.getWriter();
		JSONObject j = new JSONObject();
		//获得菜的总数
		int total = ds.getAllDishsNum();
		String page = req.getParameter("page");
		String rows = req.getParameter("rows");
		Customer customer = (Customer) session.getAttribute("customerly");
		//获得用户id
		int Uid = 0;
		if(customer != null) {
			Uid = customer.getUid();
		}
		if(page!=null && rows!=null) {
			//获得全部菜
			List<Dish_spd> dishs = ds.getAllDishs(Integer.parseInt(page), Integer.parseInt(rows));
			j.put("total", total);
			j.put("rows", dishs);
		}
		String did = req.getParameter("did");
		//获得菜id
		if(did != null) {
			Dish_spd selectDish = ds.getselectDish(Integer.parseInt(did));
			if(selectDish != null) {
				session.setAttribute("selectDish", selectDish);
				j.put("customer", customer);
				j.put("dName", selectDish.getdName());
				j.put("sName", selectDish.getsName());
				j.put("dNumber", selectDish.getdNumber());
				j.put("did", selectDish.getDid());
				j.put("rid", selectDish.getRid());
				j.put("rPrice", selectDish.getrPrice());
			}
		}
		//获得餐馆id
		String restId = req.getParameter("restId");
		//获得订菜数量
		String dishNum = req.getParameter("dishNum");
		//获得菜id
		String dishId = req.getParameter("dishId");
		//获得菜价格
		String rPrice = req.getParameter("rPrice");
		java.util.Date tempDate = new java.util.Date();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		String addTime = sdf.format(tempDate);
		if(restId!=null && dishNum!=null && dishId!=null) {
			//通过这些数据生成订单.
			boolean flag = ds.insertOrder(Uid, Integer.parseInt(restId), Integer.parseInt(dishId), Integer.parseInt(dishNum), customer.getCaddress(), Integer.parseInt(rPrice), addTime);
			if(flag) {
				j.put("isOrder", 1);
			} else {
				j.put("isOrder", 0);
			}
		}
		pw.write(j.toString());
	}
}
